package com.hzsai.schedule;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.hzsai.entity.PushSampleEntity;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * hzsai 2019/11/6
 * usage:
 **/
@Component
public class PushServer implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(PushServer.class);

    private final CustomTaskScheduler scheduler;

    @Autowired
    public SocketIOServer socketIOServer;

    //TODO:
    // 添加ThreadPoolTaskExecutor

    private PushTask task;

    @Autowired
    public PushServer(CustomTaskScheduler scheduler) {
        logger.debug("看看步骤在哪里...");
        this.scheduler = scheduler;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.debug("看看能不能初始化...");
    }

    /**
     * TODO：
     * 后续做个更加真实的示例：
     * 接入Kafka或者RabbitMQ来监听消息队列是否有消息，如果有，则推送给当前已经链接的用户
     *
     * @Scheduled 注解使用必须是无参的，返回值是void的，否则，该方法将不会被调度器调度
     *
     * Netty-Socketio的默认的namespace是 "" 详细见：`Field` com.corundumstudio.socketio.SocketIOServer.mainNamespace
     */
    public void stop() {
        scheduler.stop();
        logger.info("Task {} stopped.", Thread.currentThread().getName());
    }

    /**
     * 启动时候，开启异步线程，执行定时任务
     */
    public void start() {
        // scheduled
        scheduler.scheduleWithFixedDelay(new PushTask(), 3000);
        // start
        scheduler.start();
        logger.info("Task {} started.", Thread.currentThread().getName());
    }

    public void start(String message) {
        Runnable runnable = () -> {
            Collection<SocketIOClient> clientList = socketIOServer.getNamespace("").getAllClients();
            logger.info("sending..., client size: {}", clientList.size());
            for (SocketIOClient client : clientList) {
                client.sendEvent("commonEvent", message);
            }
        };
        scheduler.schedule(runnable);
    }
}
